package com.leng.common.utils.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.leng.common.exception.UtilException;
import com.leng.common.utils.StringUtil;

/**
 * <p>
 * json工具类
 * </p>
 *
 * @author ljk
 * @since 2021-12-28 21:41
 */
public class JsonUtil {

    private static final ObjectMapper mapper;

    static {
        mapper = new ObjectMapper();
    }

    public static <T> T jsonToObject(String jsonStr, Class<T> cls) {
        try {
            return mapper.readValue(jsonStr, cls);
        } catch (JsonProcessingException e) {
            throw new UtilException(StringUtil.format("JSON解析异常,错误信息[{}],JSON字符串[{}]", e.getMessage(), jsonStr));
        }
    }

    public static <T> T jsonToObject(String jsonStr, TypeReference<T> cls) {
        try {
            return mapper.readValue(jsonStr, cls);
        } catch (JsonProcessingException e) {
            throw new UtilException(StringUtil.format("JSON解析异常,错误信息[{}],JSON字符串[{}]", e.getMessage(), jsonStr));
        }
    }

    public static String toJsonString(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new UtilException(StringUtil.format("JSON解析异常,错误信息[{}]", e.getMessage()));
        }
    }

    public static JsonNode jsonToJsonNode(String jsonStr) {
        try {
            return mapper.readTree(jsonStr);
        } catch (JsonProcessingException e) {
            throw new UtilException(StringUtil.format("JSON转换为JsonNode异常,错误信息[{}]", e.getMessage()));
        }
    }

}
